// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MBTQuotesConnection.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge.Plugins
{
    #region Using Directives

    using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;

    using Org.OpenTrader.Framework.Enums;

    #endregion

    /// <summary>
    /// The mbt quotes Connection.
    /// </summary>
    public class MBTQuotesConnection : Connection
    {
        private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

        #region Constants and Fields

        /// <summary>
        /// The buffer.
        /// </summary>
        private readonly byte[] buffer;

        /// <summary>
        /// The host to connect to
        /// </summary>
        private readonly string host;

        /// <summary>
        /// The password
        /// </summary>
        private readonly string password;

        /// <summary>
        /// The port to connect to
        /// </summary>
        private readonly int port;

        /// <summary>
        /// The user to log in
        /// </summary>
        private readonly string user;

        /// <summary>
        /// The connected.
        /// </summary>
        private bool connected;

        /// <summary>
        /// The connecting.
        /// </summary>
        private bool connecting;

        /// <summary>
        /// The networkStream.
        /// </summary>
        private NetworkStream networkStream;

        /// <summary>
        /// The networkStreamWriter.
        /// </summary>
        private StreamWriter networkStreamWriter;

        /// <summary>
        /// The partialData.
        /// </summary>
        private string partialData;

        /// <summary>
        /// The tcpClient.
        /// </summary>
        private TcpClient tcpClient;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MBTQuotesConnection"/> class.
        /// </summary>
        /// <param name="host">
        /// The host name to connect to
        /// </param>
        /// <param name="port">
        /// The port to connect to
        /// </param>
        /// <param name="user">
        /// The user to log in
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <param name="layer">
        /// The layer owning the Connection
        /// </param>
        public MBTQuotesConnection(string host, int port, string user, string password, MBTQuotesFeedPlugin layer)
            : base(layer)
        {
            this.buffer = new byte[4096];
            this.port = port;
            this.host = host;
            this.user = user;
            this.password = password;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Status.
        /// </summary>
        public override EConnectionStatus ConnectionStatus
        {
            get
            {
                if (this.connecting)
                {
                    return EConnectionStatus.Connecting;
                }

                if (this.connected)
                {
                    return EConnectionStatus.Connected;
                }

                return EConnectionStatus.Disconnected;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The connect.
        /// </summary>
        public override Status Connect()
        {
            // Already connected
            if (this.connecting)
            {
                return Status.Failure(Identity, "Already connecting");
            }

            // We're connecting
            this.RaiseConnectingEvent();

            // Do it
            this.ConnectImpl();

            return Status.Success(Identity);
        }

        /// <summary>
        /// The disconnect.
        /// </summary>
        public override Status Disconnect()
        {
            // Not connected
            if (this.ConnectionStatus != EConnectionStatus.Connected)
            {
                return Status.Failure(Identity, "Not connected");
            }

            // We're disconnecting
            this.RaiseConnectingEvent();

            // Do it
            this.DisconnectImpl();

            return Status.Success(Identity);
        }

        /// <summary>
        /// The send data.
        /// </summary>
        /// <param name="output">
        /// The output.
        /// </param>
        public void SendData(string output)
        {
            if (output == null)
            {
                return;
            }

            // Stdout.WriteLine("MBTQuotes: Sending  \"" + message + "\"");
            this.networkStreamWriter.WriteLine(output);
            this.networkStreamWriter.Flush();
        }

        /// <summary>
        /// String representation
        /// </summary>
        /// <returns>
        /// an URL like string
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0}:{1} User={2}", this.host, this.port, this.user);
        }

        #endregion

        #region Methods

        /// <summary>
        /// The connect impl.
        /// </summary>
        private void ConnectImpl()
        {
            // Say we are trying to connect currently, to avoid multiple
            this.connecting = true;

            // Create socket endpoint
            this.tcpClient = new TcpClient { NoDelay = true, SendTimeout = 2000, ReceiveTimeout = 2000 };
            this.tcpClient.Connect(this.host, this.port);

            // Raw Stream
            this.networkStream = this.tcpClient.GetStream();

            // Stream Writer
            this.networkStreamWriter = new StreamWriter(this.networkStream);
            this.networkStreamWriter.NewLine = "\n";

            // Send authentication message
            this.SendData(string.Format("L|100={0};101={1}", this.user, this.password));

            // Let's go
            this.networkStream.BeginRead(this.buffer, 0, this.buffer.Length, this.OnData, null);

            this.connecting = false;
        }

        /// <summary>
        /// The disconnect impl.
        /// </summary>
        private void DisconnectImpl()
        {
            this.networkStream.Close();
            this.tcpClient.Close();
            this.networkStream = null;
            this.tcpClient = null;
            this.networkStreamWriter = null;
            this.connecting = false;
            this.connected = false;

            // We're disconnected
            this.RaiseDisconnectedEvent();
        }

        /// <summary>
        /// Trigerred on socket data reception
        /// </summary>
        /// <param name="r">
        /// The asunc result
        /// </param>
        private void OnData(IAsyncResult r)
        {
            try
            {
                var bytesRead = this.networkStream.EndRead(r);

                var input = String.Concat(Encoding.ASCII.GetString(this.buffer, 0, bytesRead));

                // Stdout.WriteLine("MBTQuotes: Received  \"" + input + "\"");

                // Got a previous incomplete message ?
                if (this.partialData != null)
                {
                    input = this.partialData + input;

                    // Stdout.WriteLine("  Extend: Using Previous partial \"{0}\"",this.partialData);
                    this.partialData = null;
                }

                // Incomplete message at end ?
                if (input.LastIndexOf('\n') != input.Length - 1)
                {
                    var pos = input.LastIndexOf('|') - 1;
                    this.partialData = input.Substring(pos);
                    input = input.Substring(0, pos);

                    // Stdout.WriteLine("  Cut: Setting partial \"{0}\", removing partial from input for this round", this.partialData );
                }

                // Handle line
                if (input.StartsWith("G|"))
                {
                    // Logon OK
                    // We're in
                    this.connecting = false;
                    this.connected = true;

                    // We're connected
                    this.RaiseConnectedEvent();
                }
                else if (input.StartsWith("D|"))
                {
                    // Logon KO
                    // OnStart over
                    this.DisconnectImpl();
                    return;
                }
                else
                {
                    // Messages are not related to Connection lifecycle
                    (this.Layer as MBTQuotesFeedPlugin).ProcessInput(input);
                }

                this.networkStream.BeginRead(this.buffer, (int)0, (int)this.buffer.Length, this.OnData, null);
            }
            catch
            {
            }
        }

        #endregion
    }
}